package Object;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jklu
 * 对象--->Bing返回的一页，包含一页中所有图片对象
 */

public class GooglePic {
    private List<Pic> picList = new ArrayList<Pic>();

    public List<Pic> getPicList() {
        return picList;
    }

    /**
     * 构造函数
     * @param document  调用Google接口后，返回的原始信息，Google返回的为未知类型的document，图片信息存于其中
     * @param page      当前页数
     */
    public GooglePic(String document,int page){
        //正则表达式，依次获取图片类型、图片高度、图片源地址、图片宽度、图片标题
        Pattern p = Pattern.compile("\"ity\":\"(\\w+)\",\"oh\":(\\d+),\"ou\":\"(https?://[^/]+/[^/]+[^.]+\\.(jpg|jpeg|png|webp|gif))[^\"]*\",\"ow\":(\\d+),\"pt\":\"([^\"]+)\"");
//        Pattern p = Pattern.compile("\"ity\":\"(\\w*)\",\"oh\":(\\d+),\"ou\":\"(https?[^\"]+)\",\"ow\":(\\d+),\"pt\":\"([^\"]+)");
        Matcher m = p.matcher(document);
        //图片的序号，page*100+count
        int count = 0;
        while(m.find()){
            count++;
            //为每张图片创建对象
            int number = page*100+count;
            String url = m.group(3);
            int width = Integer.parseInt(m.group(5));
            int height = Integer.parseInt(m.group(2));
            String type = m.group(1);
            //去除特殊符号
            String regex = "[`~!@#$%^&*()_\\-+=<>?:\"{}|,.\\\\/;']";
            String title = m.group(6).replaceAll("<\\\\?/?\\w+>","").replaceAll(regex,"");
            if(title.isEmpty())
                title = String.valueOf(number)+String.valueOf(width)+String.valueOf(height);
            //添加到picList集合中
            picList.add(new Pic(number,width,height,title,url,type));
        }
    }
}
